﻿/// <reference path="jquery-1.11.2.js" />
/// <reference path="jquery-ui-1.11.4.js" />
/// <reference path="bootstrap.js" />
/// <reference path="odatajs-4.0.0-beta-01.js" />

//// home

function $home() {
    //// global initialization

    $.datepicker.setDefaults($.datepicker.regional["zh-CN"]);

    //// pages

    var _pages = {
        "dashboard": {
            title: $($("#navbar > ul > li > a").get(0)).text(),
            init: function () {
                $.each(["print-sale"], function (index, target) {
                    $.get("/views/" + target + ".html")
                    .done(function (html) {
                        var setting = _pages[target];
                        $("#dialog").append(html);
                        setting.init();
                    })
                    .fail(function (xhr, status, error) {
                        alert(error);
                    });
                });
            }
        },

        "sale-management": {
            title: $($("#navbar > ul > li > a").get(1)).text(),
            init: function () {
                //// members

                var fromDatePicker = $("#sale-management-from");
                var toDatePicker = $("#sale-management-to");
                var searchButton = $("#sale-management-search");
                var searchResult = $("#sale-management-result");

                //// initialization

                fromDatePicker.datepicker({
                });
                toDatePicker.datepicker({
                });
                searchButton.click(function () {
                });
            }
        },

        "customer-management": {
            title: $($("#navbar > ul > li > a").get(2)).text(),
            init: function () {
            }
        },

        "diamond-management": {
            title: $($("#navbar > ul > li > a").get(3)).text(),
            init: function () {
            }
        },

        "control-panel": {
            title: $($("#navbar > ul > li > a").get(4)).text(),
            init: function () {
            }
        },

        "help": {
            title: $($("#navbar > ul > li > a").get(5)).text(),
            init: function () {
            }
        },

        "login": {
            init: function () {
                //// members

                var nameControl = $("#login-name");
                var passwordControl = $("#login-password");
                var messageSection = $("#login-message");
                var loginButton = $("#login-button");

                // init

                messageSection.hide();

                loginButton.click(function () {
                    odatajs.oData.request({
                        requestUri: "/securityservice/Login()",
                        method: "POST",
                        data: {
                            name: nameControl.val(),
                            password: passwordControl.val()
                        }
                    }, function (data) {
                        
                    }, function (error) {
                        messageSection.show();
                    });
                });
            }
        },

        "print-sale": {
            init: function () {
                //// members

                var sale;

                var dialog = $("#print-sale");

                var userInfo = $("#print-sale-user-info");
                var customerInfo = $("#print-sale-customer-info");
                var goodInfo = $("#print-sale-good-info");

                var customerWayButton = $("#print-sale-customer-way-button");
                var goodNameButton = $("#print-sale-good-name-button");
                var clearAllButton = $("#print-sale-clear-all");
                var clearGoodButton = $("#print-sale-clear-good");
                var clearUserButton = $("#print-sale-clear-user");
                var clearCustomerButton = $("#print-sale-clear-customer");
                var addGoodButton = $("#print-sale-add-good");
                var saveButton = $("#print-sale-save");
                var printServiceButton = $("#print-sale-print-service");
                var printReceiptButton = $("#print-sale-print-receipt");

                var userName = $("#print-sale-user");
                var receiptNumber = $("#print-sale-receipt-number");

                var customerName = $("#print-sale-customer-name");
                var customerPhone = $("#print-sale-customer-phone");
                var customerContact = $("#print-sale-customer-contact");
                var customerWay = $("#print-sale-customer-way");

                var goodName = $("#print-sale-good-name");
                var goodCertificate = $("#print-sale-good-certificate");
                var goodCaret = $("#print-sale-good-caret");
                var goodCut = $("#print-sale-good-cut");
                var goodClarity = $("#print-sale-good-clarity");
                var goodColor = $("#print-sale-good-color");
                var goodDescription = $("#print-sale-good-description");
                var goodQuantity = $("#print-sale-good-quantity");
                var goodPrice = $("#print-sale-good-price");

                var customerWayButtonHtml = customerWayButton.html();

                //// init dialog

                odatajs.oData.read("/securityservice/Users?$orderby=DisplayName desc", function (data) {
                    $.each(data.value, function (index, user) {
                        $("<option/>").val(user.Id).text(user.DisplayName).appendTo(userName);
                    });
                    construct();
                }, function (error) {
                    alert(JSON.stringify(error));
                });

                function construct() {
                    // customer way
                    $("> li > a", customerWayButton.next()).click(function () {
                        var value = $(this).attr("data-content");
                        var text = $(this).text();
                        customerWayButton.html(text + " " + customerWayButtonHtml);
                        customerWay.val(value);
                    });

                    // good name
                    $("> li > a", goodNameButton.next()).click(function () {
                        goodName.val($(this).text());
                    });

                    // dialog
                    dialog.on("shown.bs.modal", function () {
                        userName.focus();
                    });

                    // disable enable
                    function setEnabled(enabled) {
                        $("fieldset input, fieldset textarea", dialog).not(receiptNumber).prop("readonly", !enabled);
                        $("fieldset button, fieldset select", dialog).prop("disabled", !enabled);
                        if (enabled) {
                            saveButton.removeProp("disabled");
                        } else {
                            saveButton.prop("disabled", true);
                        }
                    }

                    //// cleanup

                    function cleanupUser() {
                        $home.validation.cleanup(userInfo);
                    }

                    function cleanupCustomer() {
                        $home.validation.cleanup(customerInfo);
                    }

                    function cleanupGood() {
                        $home.validation.cleanup(goodInfo);
                    }

                    function clearUser() {
                        userName.val("");
                        receiptNumber.val("");
                        cleanupUser();
                    }

                    function clearCustomer() {
                        customerName.val("");
                        customerPhone.val("");
                        customerContact.val("");
                        customerWay.val("");
                        cleanupCustomer();
                    }

                    function clearGood() {
                        goodName.val("");
                        goodCertificate.val("");
                        goodCaret.val("");
                        goodCut.val("");
                        goodClarity.val("");
                        goodColor.val("");
                        goodDescription.val("");
                        goodQuantity.val("");
                        goodPrice.val("");
                        cleanupGood();
                    }

                    clearUserButton.click(function (e) {
                        e.preventDefault();
                        clearUser();
                    });

                    clearCustomerButton.click(function (e) {
                        e.preventDefault();
                        clearCustomer();
                    });

                    clearGoodButton.click(function (e) {
                        e.preventDefault();
                        clearGood();
                    });

                    clearAllButton.click(function (e) {
                        e.preventDefault();
                        clearUser();
                        clearCustomer();
                        clearGood();
                        $("table > tbody", dialog).empty();
                        $("table > tfoot > tr > th", dialog).last().empty();
                        setEnabled(true);
                        printReceiptButton.attr("href", "javascript:void(0)");
                        printServiceButton.attr("href", "javascript:void(0)");
                        initialize();
                    });

                    //// add good

                    addGoodButton.click(function (e) {
                        e.preventDefault();

                        function formatDescription() {
                            var result = "";

                            if (goodCertificate.val().length > 0) {
                                result += "证书：" + goodCertificate.val() + " ";
                            }
                            if (goodCaret.val().length > 0) {
                                result += "钻重：" + goodCaret.val() + " ";
                            }
                            if (goodCut.val().length > 0) {
                                result += "切工：" + goodCut.val() + " ";
                            }
                            if (goodClarity.val().length > 0) {
                                result += "净度：" + goodClarity.val() + " ";
                            }
                            if (goodColor.val().length > 0) {
                                result += "颜色：" + goodColor.val() + " ";
                            }
                            if (goodDescription.val().length > 0) {
                                result += goodDescription.val();
                            }

                            return result;
                        }

                        cleanupGood();

                        if (!($home.validation.validateRequired(goodName) &&
                              $home.validation.validateFloat(goodCaret) &&
                              $home.validation.validateRequired(goodQuantity) &&
                              $home.validation.validateInteger(goodQuantity) &&
                              $home.validation.validateRequired(goodPrice) &&
                              $home.validation.validateInteger(goodPrice))) {
                            alert("请检查商品信息，有未填写的内容，请填写完整。");
                            return;
                        }

                        var quantity = parseInt(goodQuantity.val());
                        var unitPrice = parseInt(goodPrice.val());
                        var price = quantity * unitPrice;
                        $("<tr></tr>")
                            .append($("<td></td>").text(goodName.val()))
                            .append($("<td></td>").text(formatDescription()))
                            .append($("<td class='quantity'></td>").text(quantity.toString()))
                            .append($("<td class='price'></td>").text(price.toString()))
                            .appendTo("table > tbody", dialog);

                        var totalPrice = 0;
                        $.each($("table > tbody > tr", dialog), function (index, row) {
                            var price = parseInt($("td", row).last().text());
                            totalPrice += price;
                        });
                        $("table > tfoot > tr > th", dialog).last().text(totalPrice.toString());

                        var detail = {
                            ProductName: goodName.val(),
                            ProductDescription: goodDescription.val(),
                            Quantity: quantity,
                            UnitPrice: unitPrice
                        };
                        if (goodCertificate.val().length > 0) {
                            detail.Certificate = goodCertificate.val();
                        }
                        if (goodCaret.val().length > 0) {
                            detail.Caret = parseFloat(goodCaret.val());
                        }
                        if (goodCut.val().length > 0) {
                            detail.Cut = goodCut.val();
                        }
                        if (goodClarity.val().length > 0) {
                            detail.Clarity = goodClarity.val();
                        }
                        if (goodColor.val().length > 0) {
                            detail.Color = goodColor.val();
                        }
                        sale.Details.push(detail);

                        clearGood();
                    });

                    //// save

                    saveButton.click(function (e) {
                        e.preventDefault();

                        cleanupUser();
                        cleanupCustomer();

                        if (!($home.validation.validateRequired(userName))) {
                            alert("请检查用户信息，有未填写的内容，请填写完整。");
                            return;
                        }

                        if (!($home.validation.validateRequired(customerName) &&
                              $home.validation.validateRequired(customerPhone) &&
                              $home.validation.validateRequired(customerContact))) {
                            alert("请检查客户信息，有未填写的内容，请填写完整。");
                            return;
                        }

                        if (sale.Details.length === 0) {
                            alert("没有添加任何商品，请添加商品之后继续。");
                            return;
                        }

                        setEnabled(false);

                        sale.SalePersonName = $("#print-sale-user-info option:selected").text();
                        sale.CustomerName = customerName.val();
                        sale.CustomerContacts = [
                            { Method: "Phone", Value: customerPhone.val() },
                            { Method: customerWay.val(), Value: customerContact.val() }
                        ];

                        odatajs.oData.request({
                            requestUri: "/salesservice/Sales",
                            method: "POST",
                            data: sale
                        }, function (data) {
                            receiptNumber.val(data.NumberText);
                            printServiceButton.attr("href", "/views/print-service.html?id=" + data.Id);
                            printReceiptButton.attr("href", "/views/print-receipt.html?id=" + data.Id);
                            alert("保存成功，可以开始打印。");
                        }, function (error) {
                            alert(JSON.stringify(error));
                            setEnabled(true);
                        });
                    });

                    //// print

                    function validatePrint(event) {
                        if (!saveButton.prop("disabled")) {
                            event.preventDefault();
                            alert("请先保存之后再打印。");
                            return;
                        }
                    }

                    printServiceButton.click(validatePrint);
                    printReceiptButton.click(validatePrint);

                    //// initialize

                    function initialize() {
                        sale = {
                            Details: []
                        };
                        $("> li > a", customerWayButton.next()).first().click();
                    }

                    initialize();
                }
            }
        }
    };

    //// navigator

    function _navigate(target) {
        $.get("/views/" + target + ".html")
        .done(function (html) {
            var setting = _pages[target];
            $("h1").text(setting.title);
            $("#content").html(html);
            setting.init();
        })
        .fail(function (xhr, status, error) {
            alert(error);
        });
    }

    $("#navbar > ul > li > a").click(function () {
        var target = $(this).attr("data-target");
        _navigate(target);
    });

    _navigate("dashboard");
}

//// validation

$home.validation = function () {
};

$home.validation.validate = function (input, validator, control) {
    var result = validator.call($(input));

    if (!control) {
        control = $(input).parentsUntil(".form-group").parent();
    }

    if (!result && !$(control).hasClass("has-error")) {
        $(control).addClass("has-error");
    }

    return result;
};

$home.validation.cleanup = function (parent) {
    if (parent) {
        $("*", parent).removeClass("has-error");
    } else {
        $("*").removeClass("has-error");
    }
};

$home.validation.validateRequired = function (input, control) {
    return $home.validation.validate(input, function () {
        return $(this).val().length > 0;
    }, control);
};

$home.validation.validateFloat = function (input, control) {
    return $home.validation.validate(input, function () {
        if ($(this).val() !== "") {
            return parseFloat($(this).val()) > 0;
        }
        return true;
    }, control);
};

$home.validation.validateInteger = function (input, control) {
    return $home.validation.validate(input, function () {
        if ($(this).val() !== "") {
            return parseInt($(this).val()) > 0;
        }
        return true;
    }, control);
};

//// init

$(function () {
    $home();
});
